package leetcode_bin_tree_test;

import bin_tree.TreeNode;

/**
 * 二叉树的最近公共祖先
 */
public class LowestCommonAncestor {
    TreeNode ret;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root.val == p.val || root.val == q.val) {
            return root;
        }
        find(root, p, q);
        return ret;
    }

    private boolean find(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return false;
        }
        int left = find(root.left, p, q) ? 1 : 0;
        int right = find(root.right, p, q) ? 1 : 0;
        int mid = root.val == p.val || root.val == q.val ? 1 : 0;
        int sum = left + right + mid;
        if (sum == 2) {
            ret = root;
        }
        return sum > 0;
    }
}
